﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Text;
using System.Collections.Generic;

namespace Jy123.Web.Module.CarVenues
{
    public partial class CarRace : System.Web.UI.Page
    {
        private int userId;
        private int cUserId;
        private int venuesId;
        protected string ModuleId;
        private Jy123.Model.Venues_Main venues;
        private Jy123.Model.Module_Main module;
        private Jy123.Model.Public_Level level;
        private Jy123.Model.User_Main user;
        private string[] strContent = { "我的赛场", "赛场信息", "比赛实况", "赛场设备", "赛场排行", "赛场维护", "商业活动" };
        private string[] strCss = { "lmenu2", "lmenu2", "lmenu3", "lmenu2", "lmenu2", "lmenu2", "lmenu2" };
        private string[] strHeaderCss = { "", "", "NavIcon", "" };
        private string[] strHref = { "", "", "", "", "", "", "" };

        protected void Page_Load(object sender, EventArgs e)
        {
            string strUserIdFromCookie = Common.Cookie.getCookie("UserID");
            if (string.IsNullOrEmpty(strUserIdFromCookie))
            {
                Response.Redirect("/");
            }
            if (!Page.IsPostBack)
            {
                cUserId = int.Parse(strUserIdFromCookie);
                LoadInitialValue();
            }
        }

        private void LoadInitialValue()
        {
            string key = "VenuesId";
            string venuesIdString = Request.QueryString[key];
            if (!string.IsNullOrEmpty(venuesIdString))
            {
                venuesId = int.Parse(venuesIdString);
                ModuleId = venuesIdString;
                Jy123.BLL.Venues_Main BLLVenues = new Jy123.BLL.Venues_Main();

                Jy123.BLL.Module_Main BLLModuleMain = new Jy123.BLL.Module_Main();
                Jy123.BLL.Club.CModule BLLCModule = new Jy123.BLL.Club.CModule();
                Jy123.BLL.Public_Level BLLLevel = new Jy123.BLL.Public_Level();
                Jy123.BLL.User_Main BLLUser = new Jy123.BLL.User_Main();

                venues = BLLVenues.GetModel(venuesId);
                userId = venues.FUser.Value;
                user = BLLUser.GetModel(userId);
                level = BLLLevel.GetModel(venues.FLevel.Value);
                module = BLLModuleMain.GetModel(venuesId);
                BindHTML();
            }
            else
            {
                //找不到UserId，返回首页,目前暂时返回空值
            }
        }

        private void BindHTML()
        {
            string strHTML = Cache["carrace"].ToString();
            Jy123.Web.AppCode.Module appModule = new Jy123.Web.AppCode.Module();
            string strHeader = Cache["header"].ToString();
            string headerString = appModule.BindHeader(strHeader, strHeaderCss);
            string strLeft = Cache["leftmenu"].ToString();
            string strLeftLi = Cache["leftmenuli"].ToString();
            string strTail = "?VenuesId=" + venues.ID.ToString();
            string[] strHref = { "/Module/Venues/MyVenues.aspx" + strTail, "UpdateVenues.aspx" + strTail, "#", "/Module/Venues/ModuleRank.aspx" + strTail, "/Module/Venues/VenuesAnnexe.aspx" + strTail, "/Module/Venues/VenuesRepair.aspx" + strTail, "/Module/Venues/VenuesHire.aspx" + strTail };
            string leftMenuString = appModule.BindLeftMenu(strLeft, strLeftLi, strContent, strHref, strCss);
            string strClub = Cache["contentclub"].ToString();
            string contentString = appModule.BindContentClub(strClub, module, venues, user, level);
            string strMain = Cache["mainmenu"].ToString();
            string strDiv = Cache["mainmenusubdiv"].ToString();
            string strLi = Cache["mainmenusubdivli"].ToString();
            string mainMenuString = appModule.BindMainMenu(strMain, strDiv, strLi, cUserId);

            strHTML = strHTML.Replace("$Header$", headerString);
            strHTML = strHTML.Replace("$MainMenu$", mainMenuString);
            if (cUserId == userId)
            {
                strHTML = strHTML.Replace("$LeftMenu$", leftMenuString);
            }
            else
            {
                strHTML = strHTML.Replace("$LeftMenu$", string.Empty);
            }
            strHTML = strHTML.Replace("$ContentClub$", contentString);
            strHTML = strHTML.Replace("$Footer$", Cache["footer"].ToString());
            strHTML = strHTML.Replace("$VenuesName$", venues.VName);
            strHTML = strHTML.Replace("$ModuleId$", venues.ID.ToString());
            strHTML = BindSupporterRecord(strHTML);
            string strObject = Cache["flashobject"].ToString();
            string strXML = string.Format("/Module/VenuesRace/XML/{0}/{1}.xml", venues.ID, Guid.NewGuid());
            strObject = strObject.Replace("$XML$", strXML);
            strObject = strObject.Replace("$Value$", "/Cache/Module/Flash/Court.swf");
            strHTML = strHTML.Replace("$Object$", strObject);

            string strClubList = Cache["clublist"].ToString();
            Jy123.BLL.Club.CModule BLLCModule = new Jy123.BLL.Club.CModule();
            int clubJType = venues.FJType.Value + 1;
            List<Jy123.Model.Club_Main> listFriendClub = BLLCModule.FriendsEmptyClub(cUserId, clubJType, true);
            string clubListString = appModule.BindClubList(strClubList, cUserId, listFriendClub);
            strHTML = strHTML.Replace("$ClubList$", clubListString);
            string strSelClub = string.Empty;
            if (venues.VStatus.Value == Convert.ToInt32(Jy123.BLL.Public.EnumConfig.VenuesStatus.Wait))
            {
                strSelClub = venues.RaceClub;
            }
            strHTML = strHTML.Replace("$ClubId$", strSelClub);
            string mType = "Normal";
            int maxCount = 2;
            if (venues.FJType.Value == 28 || venues.FJType.Value == 33)
            {
                mType = "Car";
                maxCount = 16;
            }
            strHTML = strHTML.Replace("$MaxCount$", maxCount.ToString());
            strHTML = strHTML.Replace("$Count$", mType);
            if (venues.VStatus.Value == Convert.ToInt32(Jy123.BLL.Public.EnumConfig.VenuesStatus.Wait))
            {
                int cClubId = int.Parse(venues.RaceClub);
                BLL.Club_Main BLLClub = new Jy123.BLL.Club_Main();
                Model.Club_Main club = BLLClub.GetModel(cClubId);
                if (club.FUser.Value == cUserId)
                {
                    strHTML = strHTML.Replace("$clubliststyle$", "display:block");
                }                
            }
            strHTML = strHTML.Replace("$clubliststyle$", "display:none");
            string[] strRace = venues.RaceClub.Split(',');
            strHTML = strHTML.Replace("$RaceCount$", strRace.Length.ToString());
            Response.Write(strHTML);
        }

        private string BindSupporterRecord(string strHTML)
        {
            StringBuilder strScript = new StringBuilder();
            string strNone = "style='display:none;'";
            string strBlock = "style='display:block;'";
            Jy123.BLL.Club_Main BLLClub = new Jy123.BLL.Club_Main();
            Jy123.BLL.User_Main BLLUser = new Jy123.BLL.User_Main();
            Jy123.BLL.Public_Level BLLLevel = new Jy123.BLL.Public_Level();
            strScript.AppendFormat("<script type='text/javascript' language='javascript'>");
            switch (venues.VStatus.Value)
            {
                case 0:
                    //空闲
                    strHTML = strHTML.Replace("$Div0$", string.Empty);
                    strHTML = strHTML.Replace("$Div1$", string.Empty);
                    strHTML = strHTML.Replace("$Script$", string.Empty);
                    strHTML = strHTML.Replace("$Style$", strNone);
                    break;
                case 1:
                    //等待
                    int clubId = int.Parse(venues.RaceClub);

                    Jy123.Model.Club_Main lClub = BLLClub.GetModel(clubId);
                    Jy123.Model.User_Main lUser = BLLUser.GetModel(lClub.FUser.Value);
                    Jy123.Model.Public_Level clubLevel = BLLLevel.GetModel(lClub.FLevel.Value);
                    string strLDiv = Cache["venuesracebigdiv"].ToString();
                    
                    string strLClub = "<div id='clubInfoDiv0' class='QD3_2GameSetL1'></div>";
                    
                    strLDiv = strLDiv.Replace("$ClubInfo$", strLClub);
                    strLDiv = strLDiv.Replace("$RaceInfoDiv$", "raceInfoDiv0");
                    strLDiv = strLDiv.Replace("$UlId$", "propsInfoDiv0");
                    strHTML = strHTML.Replace("$Div0$", strLDiv);

                    strScript.Append("$(function(){fillhtml('clubInfoDiv0','/Module/Venues/VenuesClubInfo.ashx?VenuesId=" + venues.ID.ToString() + "&Mark=0'+'&random='+ Math.random())});");
                    strScript.Append("$(function(){fillhtml('raceInfoDiv0','/Module/Venues/VenuesRaceInfo.ashx?VenuesId=" + venues.ID.ToString() + "&Mark=0'+'&random='+ Math.random())});");
                    strScript.Append("$(function(){fillhtml('propsInfoDiv0','/Module/Venues/VenuesRaceProps.ashx?VenuesId=" + venues.ID.ToString() + "&CMark=0&random='+ Math.random())});");
                    break;
                case 2:
                    //比赛
                    string[] strClubId = venues.RaceClub.Split(',');
                    for (int i = 0; i < 1; i++)
                    {
                        int cClubId = int.Parse(strClubId[i]);
                        Jy123.Model.Club_Main cClub = BLLClub.GetModel(cClubId);
                        Jy123.Model.User_Main cUser = BLLUser.GetModel(cClub.FUser.Value);
                        Jy123.Model.Public_Level cClubLevel = BLLLevel.GetModel(cClub.FLevel.Value);
                        string cClubInfo = string.Format("<div id='clubInfoDiv{0}' class='QD3_2GameSetL1'></div>", i.ToString());
                        string strCDiv = Cache["venuesracebigdiv"].ToString();
                        strCDiv = strCDiv.Replace("$ClubInfo$", cClubInfo);
                        strCDiv = strCDiv.Replace("$RaceInfoDiv$", "raceInfoDiv" + i.ToString());
                        strCDiv = strCDiv.Replace("$UlId$", "propsInfoDiv" + i.ToString());
                        
                        strHTML = strHTML.Replace("$Div0$", strCDiv);
                        string strCScript = "$(function(){fillhtml('clubInfoDiv" + i.ToString() + "','/Module/CarVenues/CarClubInfo.ashx?VenuesId=" + venues.ID.ToString() + "&Mark=" + i.ToString() + "'+'&random='+ Math.random())});";
                        string strRScript = "$(function(){fillhtml('raceInfoDiv" + i.ToString() + "','/Module/CarVenues/CarRaceInfo.ashx?VenuesId=" + venues.ID.ToString() + "&Mark=" + i.ToString() + "'+'&random='+ Math.random())});"; ;
                        string strPScript = "$(function(){fillhtml('propsInfoDiv" + i.ToString() + "','/Module/CarVenues/CarRaceProps.ashx?VenuesId=" + venues.ID.ToString() + "&CMark=" + i.ToString() + "'+'&random='+ Math.random())});";
                        strScript.Append(strCScript);
                        strScript.Append(strRScript);
                        strScript.Append(strPScript);
                    }
                    strHTML = strHTML.Replace("$Style$", strBlock);
                    break;
            }
            string strFScript = "$(function(){fillhtml('objectDiv','/Module/Venues/FillRaceFlash.ashx?VenuesId=" + venues.ID.ToString() + "'+'&random='+ Math.random())});";
            string strLiScript = "$(function(){fillhtml('raceUl','/Module/CarVenues/CarUserInfo.ashx?VenuesId=" + venues.ID.ToString() + "'+'&random='+ Math.random())});";
            strScript.Append(strFScript);
            strScript.Append(strLiScript);
            strScript.AppendFormat("</script>");
            strHTML = strHTML.Replace("$Script$", strScript.ToString());
            strHTML = BindScript(strHTML);
            return strHTML;
        }

        private string BindScript(string strHTML)
        {
            StringBuilder strScript = new StringBuilder();
            string timeOut = "30000";
            strScript.Append("<script type='text/javascript' language='javascript'>");

            string strVarClubInfo = "var clubInfo0 = function(){fillhtml('clubInfoDiv0','/Module/CarVenues/CarClubInfo.ashx?VenuesId=" + venues.ID.ToString() + "&Mark='+$('#cClubHidden').val()+'&random='+ Math.random());}; ";
                strScript.Append(strVarClubInfo);
                strScript.AppendFormat(" var c0 = setInterval(clubInfo0,{0}); c0;",  timeOut);
                string strVarRaceInfo = "var raceInfo0 = function(){fillhtml('raceInfoDiv0','/Module/CarVenues/CarRaceInfo.ashx?VenuesId=" + venues.ID.ToString() + "&Mark='+$('#cClubHidden').val()+'&random='+ Math.random());}; ";
                strScript.Append(strVarRaceInfo);
                strScript.AppendFormat(" var r0 = setInterval(raceInfo0,{0}); r0;", timeOut);
                string strVarPropsInfo = "var propsInfo0 = function(){fillhtml('propsInfoDiv0','/Module/CarVenues/CarRaceProps.ashx?VenuesId=" + venues.ID.ToString() + "&CMark='+$('#cClubHidden').val()+'&random='+ Math.random());}; ";
                strScript.Append(strVarPropsInfo);
                strScript.AppendFormat(" var p0 = setInterval(propsInfo0,{0}); p0;", timeOut);            
            string strVarFlashInfo = "var flashInfo = function(){fillhtml('objectDiv','/Module/Venues/FillRaceFlash.ashx?VenuesId=" + venues.ID.ToString() + "'+'&random='+ Math.random());}; ";
            strScript.Append(strVarFlashInfo);
            strScript.AppendFormat(" var f = setInterval(flashInfo,{0}); f;", timeOut);
            string strVarUserInfo = "var userInfo0 = function(){fillhtml('raceUl','/Module/CarVenues/CarUserInfo.ashx?VenuesId=" + venues.ID.ToString() + "&CMark='+$('#cClubHidden').val()+'&random='+ Math.random());}; ";
            strScript.Append(strVarUserInfo);
            strScript.AppendFormat(" var u0 = setInterval(userInfo0,{0}); u0;", timeOut);  

            string[] strCId = venues.RaceClub.Split(',');
            if (strCId.Length > 1)
            {
                //结束比赛
                BLL.Public_Game BLLGame = new BLL.Public_Game();
                BLL.Public_JType BLLJType = new Jy123.BLL.Public_JType();
                BLL.Public_SportType BLLSportType = new Jy123.BLL.Public_SportType();
                Model.Public_JType JType = BLLJType.GetModel(venues.FJType.Value);
                Model.Public_SportType sportType = BLLSportType.GetModel(JType.FSportType.Value);
                string strGameWhere = string.Format("FVenues = {0} AND IsEnd = 0", venues.ID.ToString());
                List<Jy123.Model.Public_Game> listGame = BLLGame.GetModelList(strGameWhere);
                if (listGame.Count > 0)
                {
                    Model.Public_Game game = listGame[0];
                    string strVarEndInfo = "var endRace = function(){clearInterval(c0);clearInterval(p0);clearInterval(r0);clearInterval(f);clearInterval(u0);window.location='/Module/RaceResult.aspx?VenuesId=" + venues.ID.ToString() + "'}; ";
                    DateTime startTime = game.RaceTime.Value;
                    TimeSpan usedTime = DateTime.Now.Subtract(startTime);
                    int raceTime = sportType.RaceTime * 60 * 1000;//比赛持续时间的毫秒数
                    int usedMillSeconds = usedTime.Hours * 3600000 + usedTime.Minutes * 60000 + usedTime.Seconds * 1000 + usedTime.Milliseconds;
                    int remainingTime = raceTime - usedMillSeconds;//剩余比赛时间毫秒数                    
                    strScript.Append(strVarEndInfo);
                    strScript.AppendFormat(" setTimeout(endRace,{0}); ", remainingTime);
                }
            }
            strScript.AppendFormat("</script>");
            strHTML = strHTML.Replace("$InterValScript$", strScript.ToString());
            return strHTML;
        }
    }
}
